<script setup>
import { ref, toRefs, reactive, computed, onBeforeMount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import StringOrNumber from '../components/StringOrNumber.vue';
import CreateOrEditFrame from '../components/CreateOrEditFrame.vue';
import { listHandler } from '../../api/Generic'
import { deleteTableRow, object2List, list2Object  } from '../../utils/utils';
import Table from '../components/Table.vue';
import DialogYaml from '../components/DialogYaml.vue'
import { obj2Yaml } from '../../utils/utils';
import { createPVHandler as createHandler, updatePVHandler as updateHandler } from '../../api/pv.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  item: {
    type: Object
  }
})
const data = reactive({
  clusterId: '',
  namespace: '',
  item: {// service数据结构定义
    apiVersion: 'v1',
    kind: 'PersistentVolume',
    metadata: {
      name: '',
      labels: {},
      annotations: {},
    },
    spec: {
      capacity: {
        storage: '5Gi'
      },
      storageClassName: '',
      accessModes: ['ReadWriteMany'],
      persistentVolumeReclaimPolicy: 'Retain',
      nfs: {
        server: '',
        path: '',
        readOnly: false
      }
    }
  },
  options: {
    pvType: 'nfs',
    labelList: [],
    annotationList: [],
    dataList: [],
    rules:{
      name: [
        {required: true, message: 'PersistentVolume名称必须值', trigger: 'blur'}
      ],
      capacity: [
        {required: true, message: 'pv申请大小必须值', trigger: 'blur'}
      ],
      storageClassName: [
        {required: true, message: '请输入存储类名称', trigger: 'blur'}
      ],
      server: [
        {required: true, message: 'NFS地址必须存在', trigger: 'blur'}
      ],
      path: [
        {required: true, message: 'NFS后端路径必须存在', trigger: 'blur'},
        { pattern: '^(?=/)', message: 'NFS后端路径必须以/开头', trigger: 'blur'}
      ]
    },
    accessModes: [
      {
        label: '单节点读写',
        value: 'ReadWriteOnce'
      },
      {
        label: '多节点读写',
        value: 'ReadWriteMany'
      },
      {
        label: '多节点只读',
        value: 'ReadOnlyMany'
      },
      {
        label: '单Pod读写',
        value: 'ReadWriteOncePod'
      }
    ],
    reclaimPolicy: [
      {
        label: '保留数据',
        value: 'Retain'
      },
      {
        label: '回收数据',
        value: 'Recycle'
      },
      {
        label: '删除数据',
        value: 'Delete'
      }
    ],
  }
})
const itemRef = ref()
const activeName = ref('basic')
const labelConfig = ref('labels')
const yamlContent = ref('')
const showDetail = ref(false)

const submitRollback = (msg) => {
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '返回',
      type: 'success',
      draggable: true,
    }
  ).then(() => {
    
    router.replace({
      path: '/pv/list',// 跳转pv列表页
      query: {
        clusterId: data.clusterId,
        namespace: data.namespace
      }
    })
  }).catch(() => {
    return
  })
}

const submitHandler = (tag) => {
  data.item.metadata.labels = list2Object(data.options.labelList)
  data.item.metadata.annotations = list2Object(data.options.annotationList)

  if(tag == 'yaml') { // json转yaml
    const yamlData = obj2Yaml(data.item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: data.clusterId,
      item: data.item
    }
    if (props.method != 'Update') {
      createHandler(postData).then((response) => {
        submitRollback(response.data.message)
      })
    } else {
      updateHandler(postData).then((response) => {
        console.log(props.method)
        submitRollback(response.data.message)
      })
    }
  }
}

const submit = (tag) => {
  itemRef.value.validate((valid) => {
    if(!valid){
      ElMessage({
        message: '请完善表单',
        type: "warning"
      })
    }else {
      submitHandler(tag)
    }
  })
  

}

const rollback = (clusterId) => {
  console.log('clusterId：', clusterId)
  data.clusterId = clusterId
}

onBeforeMount(() => {
  if(props.method != 'Create'){
    data.item = JSON.parse(JSON.stringify(props.item))
    data.options.labelList = object2List(data.item.metadata.labels)
    data.options.annotationList = object2List(data.item.metadata.annotations)
    if(data.item.spec.nfs != undefined){
      console.log("编辑的类型是NFS:")
      data.options.pvType = 'nfs'
    }
  }
})

const { options, item, clusterId, namespace } = toRefs(data)
</script>

<template>
  <CreateOrEditFrame
  :show-namespace="false"
  :cluster-readonly="props.method=='Update'"
  @clusterChangedRollback="rollback"
  >
    <template #main>
      <el-form :model="item"
      center
      ref="itemRef"
      label-width="120"
      >
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="基本配置" name="basic" style="height:360px">
            <el-row :gutter="5">
              <el-col :span="8">
                <el-form-item :rules="options.rules.name" label="pv名称" prop="metadata.name" required>
                  <el-input :disabled="props.method == 'Update'" v-model="item.metadata.name" style="margin-left: 10px;width: 280px;"></el-input>
                </el-form-item>
              </el-col > 

              <el-col :span="8" v-if="options.pvType == 'nfs'">
                <el-form-item label="存储类型" prop="">
                  <el-select v-model="options.pvType" placeholder="">
                    <el-option v-for="item in ['nfs']" :key="item" :label="item" :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item :rules="options.rules.capacity" label="大小" prop="spec.capacity.storage" required>
                  <el-input v-model="item.spec.capacity.storage" style="margin-left: 10px;width:220px"></el-input>
                </el-form-item>
              </el-col>
            </el-row>



             <el-row :gutter="5" v-if="options.pvType == 'nfs'">
              <el-col :span="8">
                <el-form-item :rules="options.rules.storageClassName" label="存储类名称" prop="spec.storageClassName" required>
                  <el-input v-model="item.spec.storageClassName" style="margin-left: 10px; width: 280px;" placeholder="请输入存储类的名称，为空时为资源名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="访问策略" prop="">
                  <el-select v-model="item.spec.accessModes" multiple collapse-tags placeholder="请选择访问策略">
                    <el-option v-for="item in options.accessModes" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="回收策略" prop="">
                  <el-select v-model="item.spec.persistentVolumeReclaimPolicy" placeholder="请选择回收策略" style="margin-left: 10px;width:220px">
                    <el-option v-for="item in options.reclaimPolicy" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 存储相关配置 -->
            <el-row :gutter="5">
              <el-col :span="8">
                <el-form-item :rules="options.rules.server" label="NFS地址" prop="spec.nfs.server" required>
                  <el-input v-model="item.spec.nfs.server" style="margin-left: 10px; width: 280px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :rules="options.rules.path" label="NFS路径" prop="spec.nfs.path" required>
                  <el-input v-model="item.spec.nfs.path" style="margin-left: 10px; width: 280px;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :rules="options.rules.readOnly" label="只读" prop="">
                  <el-switch v-model="item.spec.nfs.readOnly" style="margin-left: 10px; width: 280px;"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>


          </el-tab-pane>


          <el-tab-pane label="注释及标签" name="labels" style="height:360px">
            <el-tabs v-model="labelConfig" tabPosition="left">
              <el-tab-pane label="标签配置" name="labels">
                <Table :list="options.labelList"></Table>
              </el-tab-pane>
              <el-tab-pane label="注解配置" name="annos">
                <Table :list="options.annotationList"></Table>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
        </el-tabs>
        <span style="display: block;margin-top: 30px;" class="span-button">
          <el-button @click="submit('yaml')">yaml</el-button>
          <el-button type="primary" @click="submit()">{{ props.method=="Update"?"更新":"创建" }}</el-button>
        </span>
      </el-form>
    </template>
  </CreateOrEditFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val) => { showDetail = val }"
  >
  </DialogYaml>
</template>

<style scoped>
</style>
